<template>
  <div>
    <div class="tools">
      <input type="file" @change="handleFileUpload"/>
      <div class="btn-box">
        <a-button type="primary" v-for="(item,key) in json" @click="copyToClipboard(item)">复制{{ key }}</a-button>
      </div>
    </div>
    <a-table :columns="columns" :data-source="excelData" :pagination="{ pageSize: 2000 }" :scroll="{ y: 600 }"/>
  </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import {onMounted, ref} from 'vue';

const columns = ref([])
const excelData = ref([])
const keyName = 'B'
const json = ref({})
const langKeys=ref()
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });

    // 获取第一个工作表
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    
    // 获取表头（第一行，从 C 列开始）
    const headerRow = XLSX.utils.sheet_to_json(worksheet, { header: 1, range: "C1:Z1" })[0];
    if (!headerRow) return;

    // 从第二行开始读取数据，从 C 列开始加载数据
    workbook.SheetNames.forEach(item => {
      const worksheet = workbook.Sheets[item];
      excelData.value.push(...XLSX.utils.sheet_to_json(worksheet, {header: "A", range: 1}))
    })

    // 从 C 列开始的语言列名
    langKeys.value = headerRow;

    // 检查重复值
    checkDuplicate(excelData.value, keyName);
    excelData.value.forEach(item => {
      const key = item[keyName]
      langKeys.value.forEach((langKey, index) => {
        const colLetter = String.fromCharCode('C'.charCodeAt(0) + index);
        if (!json.value[langKey]){
          json.value[langKey] = {};
        }
        if(item[colLetter]){
          json.value[langKey][key] = item[colLetter]
        }
      })
    })

    console.log(json.value)
    setColumns()
  };
  reader.readAsArrayBuffer(file);
}

const setColumns = ()=>{
  columns.value = [{
    title: 'Key',
    dataIndex: keyName,
    key: keyName
  },...langKeys.value.map((langKey, index) => {
    // 转换为 Excel 列名，支持多字母列名
    let colIndex = index + 2; // 从 C 列开始，C 列是第 3 列，索引为 2
    let colName = '';
    while (colIndex >= 0) {
      colName = String.fromCharCode('A'.charCodeAt(0) + (colIndex % 26)) + colName;
      colIndex = Math.floor(colIndex / 26) - 1;
    }
    return {
      title: langKey,
      dataIndex: colName,
      key: colName,
    };
  })];
}

const checkDuplicate = (array, propertyName) => {
  var seen = {};
  for (var i = 0; i < array.length; i++) {
    var currentValue = array[i][propertyName];
    if (seen[currentValue]) {
      console.log("位置：", i, "重复值:", currentValue)
      return true; // 发现重复值
    } else {
      seen[currentValue] = true;
    }
  }
  return false; // 没有发现重复值
}

const copyToClipboard = async (data) => {
  try {
    const result = convertToNested(data)
    const jsonString = JSON.stringify(result);
    await navigator.clipboard.writeText(jsonString);
    console.log('复制成功', result);
  } catch (err) {
    console.error('复制失败', err);
  }
};

// 将扁平键值对转换为嵌套对象
function convertToNested(flatObj) {
  const nested = {};

  for (const [key, value] of Object.entries(flatObj)) {
    const keys = key.split('.');
    let current = nested;

    // 遍历键的每一部分，创建嵌套结构
    for (let i = 0; i < keys.length - 1; i++) {
      const currentKey = keys[i];
      if (!current[currentKey]) {
        current[currentKey] = {};
      }
      current = current[currentKey];
    }

    // 设置最终值
    const finalKey = keys[keys.length - 1];
    current[finalKey] = value;
  }

  return nested;
}

onMounted(async () => {
})
</script>

<style>
.tools{
  display: flex;
  justify-content: space-between;
  background: #fff;
  padding: 10px;
  position: sticky;
  top: 0;
  z-index: 999;
}
.btn-box{
  display: flex;
  justify-content: end;
  gap: 10px;
  
}

</style>
